package com.kob.consumer;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.kob.Mapper.RecordMapper;
import com.kob.Mapper.UserMapper;
import com.kob.consumer.utils.Game;
import com.kob.consumer.utils.JwtAuthentication;
import com.kob.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{token}")
public class WebSocketServer extends Throwable{

    final public static ConcurrentHashMap<Integer,WebSocketServer> users = new ConcurrentHashMap<>();
    private User user;
    private Session session=null;

    final private static CopyOnWriteArraySet<User> matchpool = new CopyOnWriteArraySet<>();

    private Game game=null;
    private static UserMapper userMapper;
    public static RecordMapper recordMapper;


    @Autowired
    public void setRecordMapper(RecordMapper recordMapper){
        WebSocketServer.recordMapper = recordMapper;
    }

    @Autowired
    public void serUserMapper(UserMapper userMapper){
        WebSocketServer.userMapper=userMapper;
    }
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        this.session=session;
        System.out.println("connected!");
        Integer userId = JwtAuthentication.getUserId(token);
        this.user=userMapper.selectById(userId);
        if(this.user!=null){
            users.put(userId,this);
        }else{
            this.session.close();
        }
        users.put(userId,this);
    }

    @OnClose
    public void onClose() {
        // 关闭链接
        System.out.println("disconnected");
        if(this.user!=null){
            users.remove(this.user.getId());
            matchpool.remove(this.user);
        }
    }
    private void startMatching(){
        System.out.println("start");
        matchpool.add(this.user);
        while(matchpool.size()>=2){
            Iterator<User> it = matchpool.iterator();
            User a = it.next(),b=it.next();
            matchpool.remove(a);
            matchpool.remove(b);
            Game game = new Game(13,14,20,a.getId(),b.getId());
            game.createMap();
            users.get(a.getId()).game = game;
            users.get(b.getId()).game = game;
            game.start();


            JSONObject respGame = new JSONObject();
            respGame.put("a_id",game.getPlayerA().getId());
            respGame.put("a_sx",game.getPlayerA().getSx());
            respGame.put("a_sy",game.getPlayerA().getSy());

            respGame.put("b_id",game.getPlayerB().getId());
            respGame.put("b_sx",game.getPlayerB().getSx());
            respGame.put("b_sy",game.getPlayerB().getSy());

            respGame.put("map",game.getG());
            int [][]s=game.getG();

            JSONObject rA = new JSONObject();
            rA.put("event","start-matching");
            rA.put("opponent_username",b.getUsername());
            rA.put("opponent_photo",b.getPhoto());
            rA.put("gamemap",game.getG());
            rA.put("game",respGame);
            users.get(a.getId()).sendMessage(rA.toJSONString());

            JSONObject rB = new JSONObject();
            rB.put("event","start-matching");
            rB.put("opponent_username",a.getUsername());
            rB.put("opponent_photo",a.getPhoto());
            rB.put("gamemap",game.getG());
            rB.put("game",respGame);
            users.get(b.getId()).sendMessage(rB.toJSONString());
        }
    }

    private void stopMatching(){
        System.out.println("stop");
        matchpool.remove(this.user);
    }
    private void move(int direction){
        if(game.getPlayerA().getId().equals(user.getId())){
            game.setNextStepA(direction);
        }else if(game.getPlayerB().getId().equals(user.getId())){
            game.setNextStepB(direction);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 从Client接收消息
        System.out.println("receive message!");
        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event");
        if("start-matching".equals(event)){
            startMatching();
        }else if("stop-matching".equals(event)){
            stopMatching();
        }else if("move".equals(event)){
            move(data.getInteger("direction"));
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
    public void sendMessage(String message){
        synchronized (this.session){
            try{
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}